package com.stylefeng.guns.modular.customer.controller;

import cn.afterturn.easypoi.entity.vo.NormalExcelConstants;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.baomidou.mybatisplus.plugins.Page;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.base.tips.SuccessTip;
import com.stylefeng.guns.core.common.annotion.Permission;
import com.stylefeng.guns.core.common.constant.Const;
import com.stylefeng.guns.core.common.constant.factory.PageFactory;
import com.stylefeng.guns.core.common.exception.BizExceptionEnum;
import com.stylefeng.guns.core.exception.GunsException;
import com.stylefeng.guns.core.log.LogObjectHolder;
import com.stylefeng.guns.core.support.BeanKit;
import com.stylefeng.guns.core.support.VlidationUtil;
import com.stylefeng.guns.modular.customer.dao.ContactDao;
import com.stylefeng.guns.modular.customer.service.IContactService;
import com.stylefeng.guns.modular.customer.transfer.ContactXlsM;
import com.stylefeng.guns.modular.customer.util.CustomerUtil;
import com.stylefeng.guns.modular.customer.warpper.ContactWrapper;
import com.stylefeng.guns.modular.system.model.Contact;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.flowable.bpmn.model.DataGrid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.naming.NoPermissionException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * 联系人控制器
 *
 * @author fengshuonan
 * @Date 2018-04-02 11:41:22
 */
@Controller
@RequestMapping("/contact")
public class ContactController extends BaseController {

    private String PREFIX = "/customer/contact/";

    @Autowired
    private IContactService contactService;
    @Autowired
    private ContactDao contactDao;


    /**
     * 跳转到联系人首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "contact.html";
    }

    /**
     * 跳转到添加联系人
     */
    @RequestMapping("/contact_add")
    public String contactAdd() {
        return PREFIX + "contact_add.html";
    }

    /**
     * 跳转到修改联系人
     */
    @RequestMapping("/contact_update/{contactId}")
    public String contactUpdate(@PathVariable Integer contactId, Model model) {
        Contact contact = contactService.selectById(contactId);
        Map<String, Object> map = BeanKit.beanToMap(contact);
        model.addAttribute("item", new ContactWrapper(map).warp());
        LogObjectHolder.me().set(contact);
        return PREFIX + "contact_edit.html";
    }

    /**
     * 获取联系人列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(@RequestParam(required = false) String name
                        ,@RequestParam(required = false) String customerCompanyName) {
        Page<Contact> page = new PageFactory<Contact>().defaultPage();
        List<Map<String, Object>> list = this.contactDao.page(page, name,customerCompanyName);
        page.setRecords((List<Contact>) new ContactWrapper(list).warp());
        return super.packForBT(page);
    }

    /**
     * 新增联系人
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    @Permission
    @ApiOperation(value = "新增联系人", tags = "联系人", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "name", value = "名字", dataType = "string", required = true),
                    @ApiImplicitParam(name = "departName", value = "部门名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "post", value = "职务", dataType = "string", required = true),
                    @ApiImplicitParam(name = "mobileNum", value = "手机号", dataType = "string", required = true),
                    @ApiImplicitParam(name = "standbyMobileNum", value = "备用手机号", dataType = "string", required = false),
                    @ApiImplicitParam(name = "landline", value = "办公电话", dataType = "string", required = false),
                    @ApiImplicitParam(name = "facsimile", value = "传真", dataType = "string", required = false),
                    @ApiImplicitParam(name = "email", value = "电子邮箱", dataType = "string", required = false),
                    @ApiImplicitParam(name = "wechat", value = "微信号", dataType = "string", required = false),
                    @ApiImplicitParam(name = "qq", value = "qq", dataType = "long", required = false),
                    @ApiImplicitParam(name = "attitude", value = "态度", dataType = "string", required = false),
                    @ApiImplicitParam(name = "remark", value = "备注", dataType = "string", required = false),
            }
    )
    public Object add(@Valid Contact contact) {
        contactService.insert(contact);
        return SUCCESS_TIP;
    }

    /**
     * 删除联系人
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    @Permission(Const.ADMIN_NAME)
    public Object delete(@RequestParam Integer contactId) {
        contactService.deleteById(contactId);
        return SUCCESS_TIP;
    }

    /**
     * 修改联系人
     */
    @RequestMapping(value = "/update")
    @ResponseBody
    @Permission
    @ApiOperation(value = "更新联系人", tags = "联系人", httpMethod = "POST", code = 200, response = SuccessTip.class)
    @ApiImplicitParams(
            {
                    @ApiImplicitParam(name = "id", value = "id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "name", value = "名字", dataType = "string", required = true),
                    @ApiImplicitParam(name = "departName", value = "部门名称", dataType = "string", required = true),
                    @ApiImplicitParam(name = "customerCompanyId", value = "客户id", dataType = "integer", required = true),
                    @ApiImplicitParam(name = "post", value = "职务", dataType = "string", required = true),
                    @ApiImplicitParam(name = "mobileNum", value = "手机号", dataType = "string", required = true),
                    @ApiImplicitParam(name = "standbyMobileNum", value = "备用手机号", dataType = "string", required = false),
                    @ApiImplicitParam(name = "landline", value = "办公电话", dataType = "string", required = false),
                    @ApiImplicitParam(name = "facsimile", value = "传真", dataType = "string", required = false),
                    @ApiImplicitParam(name = "email", value = "电子邮箱", dataType = "string", required = false),
                    @ApiImplicitParam(name = "wechat", value = "微信号", dataType = "string", required = false),
                    @ApiImplicitParam(name = "qq", value = "qq", dataType = "long", required = false),
                    @ApiImplicitParam(name = "attitude", value = "态度", dataType = "string", required = false),
                    @ApiImplicitParam(name = "remark", value = "备注", dataType = "string", required = false),
            }
    )
    public Object update(@Validated Contact contact) throws NoPermissionException {
        Contact dbContact = this.contactService.selectById(contact.getId());
        if (dbContact == null) {
            return new GunsException(BizExceptionEnum.REQUEST_NULL);
        }
        CustomerUtil.validEditPermission(dbContact.getCustomerCompanyId());
        contactService.updateById(contact);
        return SUCCESS_TIP;
    }

    @RequestMapping(value = "/contact_detail/{customerCompanyId}")
    public Object toDetail(@PathVariable("customerCompanyId") Integer customerCompanyId, Model model) {
        List<Map<String, Object>> list = contactDao.selectByCompanyId(customerCompanyId);
        model.addAttribute("items", new ContactWrapper(list).warp());
        return PREFIX + "contact_detail.html";
    }

    /**
     * 联系人详情
     */
    @RequestMapping(value = "/detail/{contactId}")
    @ResponseBody
    public Object detail(@PathVariable("contactId") Integer contactId) {

        Contact contact = contactService.selectById(contactId);
        if (contact == null) {
            throw new GunsException(BizExceptionEnum.DB_RESOURCE_NULL);
        }

        Map<String, Object> map = BeanKit.beanToMap(contact);

        if (CustomerUtil.validEditPermission(contact.getCustomerCompanyId())) {
            map.put(Const.AUTHORITY_FIELD_NAME, 1);
        }else{
            map.put(Const.AUTHORITY_FIELD_NAME, -1);
        }

        return new ContactWrapper(map).warp();
    }

    /**
     * 导出Excel模板
     *
     * @param request
     * @param response
     */
    @RequestMapping(value = "/exportXlsByM", headers = {"Accept=application/vnd.ms-excel"})
    public String exportXlsByT(HttpServletRequest request, HttpServletResponse response
            , DataGrid dataGrid, ModelMap modelMap) {
        modelMap.put(NormalExcelConstants.FILE_NAME, "联系人模板");
        modelMap.put(NormalExcelConstants.CLASS, ContactXlsM.class);
        modelMap.put(NormalExcelConstants.PARAMS, new ExportParams("联系人列表",
                "导出信息"));
        modelMap.put(NormalExcelConstants.DATA_LIST, ContactXlsM.example());
        return NormalExcelConstants.EASYPOI_EXCEL_VIEW;
    }

    @RequestMapping(method = RequestMethod.POST, path = "/importExcel")
    @ResponseBody
    public Object importExcel(MultipartHttpServletRequest multipartHttpServletRequest) throws Exception {
        Map<String, MultipartFile> multipartFileMap = multipartHttpServletRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : multipartFileMap.entrySet()) {
            MultipartFile file = entity.getValue();//获取文件上传对象
            ImportParams importParams = new ImportParams();
            importParams.setTitleRows(1);
            importParams.setHeadRows(1);
            //是否需要保存上传的EXCEL
            importParams.setNeedSave(false);
            List<ContactXlsM> result = ExcelImportUtil.importExcel(file.getInputStream(), ContactXlsM.class, importParams);
            VlidationUtil.validateList(result);
            contactService.insertXlsList(result);
        }
        return "文件导入成功";
    }


}